/* eslint-disable react/jsx-no-undef */
/* eslint-disable react-hooks/exhaustive-deps */
/* eslint-disable react/jsx-key */
import React, { useState, useRef, useMemo, useEffect } from 'react';
import ReactDOM from 'react-dom';
import { Card, Switch, Button, Modal, message, Popconfirm, Tooltip } from 'antd';
import AutoTable from '@/components/AutoTable';
import InitForm from '@/components/InitForm';
import { deleteinvoice } from '@/services/business';
import { connect } from 'umi';
import { PlusOutlined, ExportOutlined } from '@ant-design/icons';
import { company } from '@/services/business';
import { getFetch } from '@/utils/doFetch';
import { area, classify, user } from '@/services/basic';
import CompanyDetail from '@/components/CompanyDetail';
import { useRequest } from 'ahooks';
import CompanyName from '@/components/CompanyName';


// type 类型有 table treeselect upload inputnumber datepicker daterange radio select textarea autoinput editor password input

function Invoice(props) {
  let defaultFields = {
    company_id: {
      value: null,
      type: 'select',
      title: '代账公司',
      name: ['company_id'],
      required: true,
      options: {
        database: company,
        params: {
          is_all: 1,
          type: -1,
          status: 'completed',
        },
      },
      col: { span: 24 },
    },
    invoice_date: {
      value: null,
      type: 'datepicker',
      title: '开票日期',
      name: ['invoice_date'],
      required: true,
      col: { span: 24 },
    },
    invoice_num: {
      value: null,
      type: 'inputnumber',
      title: '开票数量',
      name: ['invoice_num'],
      required: true,
      col: { span: 12 },
    },
    amount: {
      value: null,
      type: 'inputnumber',
      title: '开票金额',
      name: ['amount'],
      required: true,
      col: { span: 12 },
    },
    invoice_rate: {
      value: null,
      type: 'select',
      title: '开票金额税率',
      name: ['invoice_rate'],
      required: true,
      col: { span: 24 },
    },
    is_ticketed: {
      value: null,
      type: 'checkbox',
      title: '是否为小规模专票',
      name: ['is_ticketed'],
      col: { span: 24 },
      options: [
        {
          label: '是',
          value: true,
        }
      ],
    },
  };
  const [vs, cvs] = useState(false), //表单显/隐
    [fields, cf] = useState(defaultFields),
    [iftype, ciftype] = useState({});

  const { data } = useRequest(async () => {
    let res = await getFetch({ url: '/wbn-api/invoice_setting' });
    return res?.data?.added_tax_rate?.map((it) => ({
      label: it,
      value: it,
    }));
  });

  useEffect(() => {
    cf((fields) => {
      for (let i in fields) {
        if (i === 'invoice_rate') {
          fields[i].options = data;
        }
      }
      return { ...fields };
    });
  }, [data]);

  let actionRef = useRef(),
    formRef = useRef(),
    ChildRef = null;

  function reload() {
    actionRef?.current?.reload();
    ChildRef?.onRefresh();
  }

  const columns = useMemo(() => {
    return [
      {
        title: '公司名称',
        width: 260,
        dataIndex: 'company_name',
        key: 'company_name',
        render: (_, row) => (
          <CompanyName
            row={{ ...row, name: row?.company_name ?? row?.name, id: row?.company_id ?? row?.id }}
            reload={reload}
          />
        ),
      },
      {
        title: '编号',
        dataIndex: 'company_code',
        key: 'company_code',
        search: false,
      },
      {
        title: '公司类型',
        dataIndex: 'classify_name',
        key: 'classify_id',
        valueType: 'select',
        options: {
          database: classify,
          params: { is_all: 1 },
        },
      },
      {
        title: '记账会计', // 记账会计：account_name
        dataIndex: 'account_name',
        key: 'account_name',
      },
      {
        title: '开票日期',
        dataIndex: 'invoice_date',
        key: 'invoice_date',
        search: false,
      },
      {
        title: '开票数量',
        dataIndex: 'invoice_num',
        key: 'invoice_num',
        search: false,
      },
      {
        title: '开票金额',
        dataIndex: 'amount',
        key: 'amount',
        search: false,
      },
      {
        title: '名义税率',
        dataIndex: 'titular_classify_tax_rate',
        key: 'titular_classify_tax_rate',
        search: false,
      },
      {
        title: '实际税率',
        dataIndex: 'actual_classify_tax_rate',
        key: 'actual_classify_tax_rate',
        search: false,
      },
      {
        title: '操作',
        valueType: 'option',
        width: 100,
        render: (text, record, _, action) => [
          <a
            style={{ color: '#1890ff' }}
            onClick={() => {
              cvs(true);
              cf((fields) => {
                for (let i in fields) {
                  fields[i].value = record[i];
                }
                return { ...fields };
              });
              ciftype({
                val: 'edit',
                title: '编辑发票',
                id: record.id,
              });
              let nos = 0;
              if (record.amount && record.invoice_rate) {
                nos = record.amount / (1 + parseFloat(record.invoice_rate));
                setRedata((s) => ({
                  nos: nos.toFixed(2),
                  se: (record.amount - nos)?.toFixed(2),
                }));
              }
            }}
          >
            编辑
          </a>,
          <Popconfirm
            placement="bottom"
            title={'确认删除该发票？'}
            onConfirm={() => {
              deleteinvoice(record.id).then((res) => {
                if (res.code == 0) {
                  message.success('操作成功');
                  reload();
                }
              });
            }}
            okText="删除"
            cancelText="取消"
          >
            <a style={{ color: '#f50' }}>删除</a>
          </Popconfirm>,
        ],
      },
    ];
  }, []);

  let extrarender = [
    <div
      className="action"
      title="新增"
      onClick={() => {
        cvs(true);
        cf((fields) => {
          for (let i in fields) {
            fields[i].value = null;
          }
          return { ...fields };
        });
        ciftype({
          val: 'add',
          title: '新增发票',
        });
        setRedata((s) => ({
          nos: 0,
          se: 0,
        }));
      }}
    >
      <PlusOutlined />
    </div>,
    <Tooltip title="导出发票">
      <div
        className="action"
        onClick={() => {
          const hide = message.loading('正在导出..', 0);
          const params = formRef.current.getFieldsValue();
          getFetch({
            url: '/wbn-api/invoice/batch_import',
            params: { ...params },
          }).then((res) => {
            window.open(res?.data);
            hide();
          });
        }}
        style={{ marginLeft: 12 }}
      >
        <ExportOutlined />
      </div>
    </Tooltip>,
  ];

  let saveData = (values) => {
    let { dispatch } = props;
    if (iftype.val == 'add') {
      dispatch({
        type: 'business/addinvoice',
        payload: values,
      }).then((res) => {
        if (res.code == 0) {
          message.success('操作成功');
          reload();
          cvs(false);
        }
      });
    } else if (iftype.val == 'edit') {
      dispatch({
        type: 'business/editinvoice',
        payload: { ...values, id: iftype.id },
      }).then((res) => {
        if (res.code == 0) {
          message.success('操作成功');
          reload();
          cvs(false);
        }
      });
    }
  };

  const [selectid, setSelectid] = useState(null);
  const [redata, setRedata] = useState({
    nos: 0,
    se: 0,
  });
  return (
    <div className="pgcontainer">
      <AutoTable
        pagetitle={props.route.name} //页面标题
        pageextra={extrarender} //页面操作 新增or批量删除
        columns={columns}
        formRef={formRef}
        actionRef={actionRef}
        onRef={(node) => (ChildRef = node)}
        path="/wbn-api/invoice"
        //withCard={false}
        //cardtitle = "name" //卡片标题
        //cardavatar = "img_url" //卡片头像
      />
      <Modal
        maskClosable={false}
        title={iftype.title}
        open={vs}
        onCancel={() => cvs(false)}
        footer={false}
        destroyOnClose={true}
        width={680}
      >
        <CompanyDetail
          id={selectid}
          col={{ md: 2 }}
          only={['classify_name']}
          // setExpandData={(vals) => {
          //   if (vals.classify_name.indexOf('小规模') !== -1) {
          //     cf((s) => {
          //       return {
          //         ...s,
          //         is_ticketed:{
          //           ...s.is_ticketed,
          //           hides:false
          //         }
          //       };
          //     });
          //   } else {
          //     cf((s) => {
          //       return {
          //         ...s,
          //         is_ticketed:{
          //           ...s.is_ticketed,
          //           hides:true
          //         }
          //       };
          //     });
          //   }
          // }}
        />

        <InitForm
          fields={fields}
          submitData={(values) => {
            saveData(values);
          }}
          onChange={async (changedValues, allValues) => {
            //联动操作
            if (Object.keys(changedValues)[0] === 'company_id') {
              setSelectid(Object.values(changedValues)[0]);
            }
            let nos = 0;
            if (allValues.amount && allValues.invoice_rate) {
              nos = allValues.amount / (1 + parseFloat(allValues.invoice_rate));
              setRedata((s) => ({
                nos: nos.toFixed(2),
                se: (allValues.amount - nos)?.toFixed(2),
              }));
            }
          }}
          submitting={
            props.loading.effects['business/addinvoice'] ||
            props.loading.effects['business/editinvoice'] ||
            !vs
          }
        />

        <p className="spread">
          <span>不含税金额</span>
          <b>{redata?.nos ?? 0} 元</b>
        </p>
        <p className="spread">
          <span>税额</span>
          <b>{redata?.se ?? 0} 元</b>
        </p>
      </Modal>
    </div>
  );
}

export default connect(({ business, loading, user }) => ({
  business,
  loading,
  user,
}))(Invoice);
